//
//  MLRefreshControl.swift
//  MLWeiBo
//
//  Created by wenxing on 2017/1/11.
//  Copyright © 2017年 Se7venX. All rights reserved.
//

import UIKit

let refreshHeight:CGFloat = 60

enum RefreshStatus:Int {
    case Normal = 0
    case Already
    case Refreshing
}

class MLRefreshControl: UIControl {
    
    
    var faterView:UIScrollView?
    
    var  status:RefreshStatus = .Normal {
    
        didSet{
        
            switch status {
            case .Normal:
                print("Normal")
                
                self.tipLabel.text = "下拉刷新"
                self.arrowImageView.isHidden = false
                
                UIView.animate(withDuration: 0.25, animations: {
                    
                    
                    if oldValue == .Refreshing {
                        
                        self.indicationView.stopAnimating()
                        self.faterView?.contentInset.top =  (self.faterView?.contentInset.top )! - refreshHeight
                    }
                    
                    
                    self.arrowImageView.transform = CGAffineTransform.identity
                })
                
                
                
            case .Already:
                print("Already")
                
                self.tipLabel.text = "松手起飞"
                self.arrowImageView.isHidden = false
                
                UIView.animate(withDuration: 0.25, animations: {
                    
                    
                    self.arrowImageView.transform = CGAffineTransform.init(rotationAngle: CGFloat(M_PI))
                    
                }, completion: { (iSuc) in
                    
                    
                })
                
                
            case .Refreshing:
                print("Refreshing")
                
                self.arrowImageView.isHidden = true
                self.tipLabel.text = "正在刷新中......"
                self.indicationView.startAnimating()
                
                self.sendActions(for: .valueChanged)
                
                self.faterView?.contentInset.top =   (self.faterView?.contentInset.top)! + refreshHeight

            default:
                print("此处注意:::")
            }
        }
    }
    
    
    /// 结束刷新
   public func endRefreshing() {
        
        
        DispatchQueue.main.asyncAfter(wallDeadline: DispatchWallTime.now()+0.5, execute: {
            
            print("刷新完成")
            self.status = .Normal
            
        })
        
    }
    
    
    
    override init(frame: CGRect) {
        
        let rect = CGRect(x: 0, y: -refreshHeight, width: screenW, height: refreshHeight)
        
        super.init(frame: rect)
        
        self.backgroundColor = UIColor.red
        
        setupUI()
        
    }
    
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        
        if let father = newSuperview as? UIScrollView {
            
            self.faterView = father
            
//            print("此处注意:::",father)
            father.addObserver(self, forKeyPath: "contentOffset", options: [.new], context: nil)
        }
        
        
    }
    
    //MARK:- 设置UI -
    private func setupUI() {
        
        addSubview(tipLabel)
        addSubview(arrowImageView)
        addSubview(indicationView)
        
        tipLabel.snp.makeConstraints { (make) in
            
            make.centerX.equalTo(self).offset(10)
            make.centerY.equalTo(self)
        }
        
        arrowImageView.snp.makeConstraints { (make) in
            
            make.centerY.equalTo(self)
            make.right.equalTo(tipLabel.snp.left).offset(-5)
        }
        
        indicationView.snp.makeConstraints { (make) in
            
            make.edges.equalTo(arrowImageView)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
        
    }
    
    
    //MARK:- KVO 的方法 -
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

        let offsetY = self.faterView?.contentOffset.y ?? 0
        let targetY = -((self.faterView?.contentInset.top)! +  refreshHeight) //-124
        
//        print("offsetY--------------------",offsetY)
//        print("targetY:::",targetY)
        
        
        //正在拽
        if self.faterView?.isDragging == true{
            
            if status == .Already && offsetY > targetY { //上面
                
               status = .Normal
                
            }else if status == .Normal && offsetY < targetY { //下面  防止一直上下动，改变箭头
            
               status = .Already
            }
        }
        // 松掉
        else{
        
            if status == .Already {
                
                status = .Refreshing
            }
        }
    }
    
    //MARK:- Lazy -
    private lazy var tipLabel = UILabel(title: "下拉刷新", titleColor: UIColor.orange, fontSize: 18)
    
    private lazy var arrowImageView = UIImageView(image: #imageLiteral(resourceName: "tableview_pull_refresh"))
    
    lazy var indicationView: UIActivityIndicatorView = {
        
        let indiV = UIActivityIndicatorView()
        
//        indiV.startAnimating()
        
        return indiV
    }()
    
}
